/*
 * @(#)GetCookieMethod.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.macro.method.component;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * @author Web Platform Development Team
 */
public class GetCookieMethod implements TemplateMethodModelEx {
    Log log = LogFactory.getLog(GetCookieMethod.class);

    /**
     * @param args the arguments
     * @return the cookie object
     * @throws TemplateModelException the TemplateModelException
     */
    @SuppressWarnings("unchecked")
	public Object exec(List args) throws TemplateModelException {

        if (args.size() != 2) {
            throw new IllegalArgumentException();
        }

        TemplateModel model = (TemplateModel)args.get(0);
        String cookieName = String.valueOf(args.get(1));
        Object obj = BeansWrapper.getDefaultInstance().unwrap(model, HttpServletRequest.class);

        if (!(obj instanceof HttpServletRequest)) {
            throw new IllegalArgumentException();
        }

        HttpServletRequest request = (HttpServletRequest)obj;

        if (log.isDebugEnabled()) {
            log.debug("Cookie Name :" + cookieName + " from " + request);
        }

        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return null;
        }

        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie;
            }
        }

        return null;
    }
}
